package com.service.impl;

import com.mapper.ChatMapper;
import com.pojo.ChatMessage;
import com.service.ChatService;
import com.service.UserService;
import com.vo.ChatMessageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChatServiceImpl implements ChatService {

    @Autowired
    private ChatMapper chatMapper;

    @Autowired
    private UserService userService;

    @Override
    @Transactional
    public ChatMessageVO saveChatMessage(ChatMessage message) {
        message.setCreatedAt(LocalDateTime.now());
        message.setIsRead(false);
        chatMapper.insertMessage(message);

        // 转换为VO并设置用户信息
        ChatMessageVO vo = new ChatMessageVO();
        vo.setId(message.getId());
        vo.setSenderId(message.getSenderId());
        vo.setReceiverId(message.getReceiverId());
        vo.setContent(message.getContent());
        vo.setCreatedAt(message.getCreatedAt());
        vo.setIsRead(message.getIsRead());
        vo.setSenderUser(userService.getUserDTOById(message.getSenderId().longValue()).getData());

        return vo;
    }

    @Override
    @Transactional
    public void markMessageAsRead(Integer messageId, Integer userId) {
        chatMapper.updateReadStatus(messageId, userId, true);
    }

    @Override
    public List<ChatMessageVO> getChatHistory(Integer userId1, Integer userId2, int page, int size) {
        int offset = (page - 1) * size;
        return chatMapper.getMessagesBetweenUsers(userId1, userId2, offset, size)
                .stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public int countUnreadMessages(Integer userId) {
        return chatMapper.countUnreadByUserId(userId);
    }

    private ChatMessageVO convertToVO(ChatMessage message) {
        ChatMessageVO vo = new ChatMessageVO();
        vo.setId(message.getId());
        vo.setSenderId(message.getSenderId());
        vo.setReceiverId(message.getReceiverId());
        vo.setContent(message.getContent());
        vo.setCreatedAt(message.getCreatedAt());
        vo.setIsRead(message.getIsRead());
        vo.setSenderUser(userService.getUserDTOById(message.getSenderId().longValue()).getData());
        return vo;
    }
}